#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time   : 2021/7/15 22:30
# @Author : cjw
import logging
import sys
import os

from concurrent_log_handler import ConcurrentRotatingFileHandler
from server_task.setting import LOG_PATH

LOG_NAME = None
LOG_FILE = os.path.join(LOG_PATH, 'case.log')
LOG_LEVEL = logging.INFO
LOG_FORMATTER = ('%(asctime)s [%(levelname)s] %(message)s (%(filename)s:%(lineno)s)', None)


def create_logger(log_name: str = LOG_NAME,
                  log_file: str = LOG_FILE,
                  log_level: int = LOG_LEVEL,
                  log_formatter: tuple = LOG_FORMATTER):
    """
    :param log_name: 日志名称
    :param log_file: 日志文件位置
    :param log_level: 日志等级
    :param log_formatter: 日志格式
    :return:
    """
    # 日志文件夹不存在，则创建文件夹
    if not os.path.exists(LOG_PATH):
        os.mkdir(LOG_PATH)

    # 日志记录器
    logger = logging.getLogger(log_name)
    logger.setLevel(log_level)
    formatter = logging.Formatter(*log_formatter)

    # 判断是否有handlers, 有直接记录日志, 不需要创建多个句柄，否则会有日志重复打印问题
    if not logger.handlers:
        # 文件输出：达到512K后轮换日志，保留5份旧拷贝
        rotate_handler = ConcurrentRotatingFileHandler(log_file, "a", 512 * 1024, 5, encoding='utf-8')
        rotate_handler.setLevel(logging.INFO)
        rotate_handler.setFormatter(formatter)

        # 控制台输出
        stream_handler = logging.StreamHandler(sys.stdout)
        stream_handler.setLevel(logging.INFO)
        stream_handler.setFormatter(formatter)

        # 关联日志记录器和处理器
        logger.addHandler(rotate_handler)
        logger.addHandler(stream_handler)

    return logger


logger = create_logger()
